import { NextRequest, NextResponse } from 'next/server';
import { getUserManagement } from '@/lib/user-management';
import { cookies } from 'next/headers';

export async function GET(request: NextRequest) {
  try {
    const cookieStore = await cookies();
    const sessionToken = cookieStore.get('session_token')?.value;

    if (!sessionToken) {
      return NextResponse.json({
        success: false,
        error: '未登录'
      }, { status: 401 });
    }

    const userMgmt = getUserManagement();
    const user = userMgmt.validateSession(sessionToken);

    if (!user) {
      // 清除无效的cookie
      cookieStore.delete('session_token');
      return NextResponse.json({
        success: false,
        error: '会话已过期'
      }, { status: 401 });
    }

    const permissions = userMgmt.parseRolePermissions(user.role_permissions);

    return NextResponse.json({
      success: true,
      data: {
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          full_name: user.full_name,
          role_code: user.role_code,
          role_name: user.role_name,
          permissions
        }
      }
    });

  } catch (error) {
    console.error('获取用户信息失败:', error);
    return NextResponse.json({
      success: false,
      error: '获取用户信息失败'
    }, { status: 500 });
  }
}
